package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Dispatch;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.DispatchService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 控制器 - 公告通知登记表测试
 * ============================================================================
 * 版权所有 2016 。
 *
 * @version 1.0 2016-12-28 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/com/dispatch")
public class DispatchController extends BaseController {


    private static final long serialVersionUID = 805754390233185425L;
    @Autowired
    private UserService userService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DispatchService dispatchService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> typeDict = getDictItems(user,"dispatchType");
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            Dispatch dispatch = dispatchService.get(keyId);
            if(dispatch.getFile() != null && dispatch.getFile().size()>0){
                for(FileManage f:dispatch.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("keyId", keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("dispatch", dispatch);
        }
        model.addAttribute("typeDict", typeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/dispatch_input";
    }



    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> typeDict = getDictItems(user,"dispatchType");
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Dispatch dispatch = dispatchService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            if(dispatch.getFile() != null && dispatch.getFile().size()>0){
                for(FileManage f:dispatch.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            List<Map<String,Object>> examObject = Lists.newArrayList();
            Department department = null;
            List<Department> departmentList = departmentService.getDepartments("产业中心");
            if(departmentList.size()>0){
                department = departmentList.get(0);
            }
            Post post = postService.get("name", "书记");
            Post post2 = postService.get("name", "主任");
            List<Post> postList = Lists.newArrayList();
            postList.add(post);
            postList.add(post2);
            Map<String,Object> rmap;
            if(department != null ){
                for(Post post1:postList){
                    if(post1 != null){
                        rmap= Maps.newHashMap();
                        Power power = powerService.getPowerByDepartAndPost(department, post1);
                        rmap.put("id", power.getId());
                        rmap.put("name", power.getDepartment().getName()+ " - " + power.getPost().getName() );
                        rmap.put("checked","");
                        for(Power power1:dispatch.getExamObject()){
                            if(StringUtils.equals(power1.getId(),power.getId())){
                                rmap.put("checked","checked");
                            }
                        }
                        examObject.add(rmap);
                    }
                }
            }
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("fileId", fileId);
            model.addAttribute("dispatch", dispatch);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("examObject",examObject);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("typeDict", typeDict);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/dispatch_read";
    }

    /**
     * 赋值数据
     */
    private Dispatch setData(User user, String keyId, String typedictId, String title, String fileNo,
                         String time,String object,String hasValid,String validDate,String noticeDepartmentId,
                         String noticeUserId,String fileIds){
        Dispatch dispatch = null;
        if(StringUtils.isNotEmpty(keyId)){
            dispatch = dispatchService.get(keyId);
        }else{
            dispatch = new Dispatch();
            dispatch.setCreater(user);
        }
        if(StringUtils.isNotEmpty(typedictId)){
            dispatch.setType(dictItemService.get(typedictId));
        }
        dispatch.setTitle(title);
        dispatch.setFileNo(fileNo);
        if(StringUtils.isNotEmpty(time)){
            dispatch.setTime(DataUtil.StringToDate(time));
        }
        dispatch.setObject(object);
        dispatch.setHasValid((hasValid != null && hasValid.equals("1")) ? true : false);
        if(StringUtils.isNotEmpty(validDate)){
            dispatch.setValidDate(DataUtil.StringToDate(validDate));
        }
        List<Department> departmentList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(noticeDepartmentId)){
            String[] idArr = noticeDepartmentId.split(",");
            for(String id:idArr){
                departmentList.add(departmentService.get(id.trim()));
            }
        }
        List<User> userList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(noticeUserId)){
            String[] idArr = noticeUserId.split(",");
            for(String id:idArr){
                userList.add(userService.get(id.trim()));
            }
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        String dutyIds = "";
        Set<Duty> dutySet = Sets.newHashSet();
        if(StringUtils.equals(object, "1") == true){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("state", BaseEnumManager.StateEnum.Enable);
            dutySet.addAll(dutyService.getList(map));
        }else if(StringUtils.equals(object,"2") == true){
            for(Department department:departmentList){
                dutySet.addAll(dutyService.getDutys(department));
            }
        }else if(StringUtils.equals(object,"3") == true){
            for(User user1: userList){
                dutySet.addAll(dutyService.getDutys(user1));
            }
        }
        for(Duty duty:dutySet){
            dutyIds += duty.getId()+",";
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(dutyIds)){
            dutyIds = dutyIds.substring(0, dutyIds.length()-1);
        }
        dispatch.setDutyIds(dutyIds);
        dispatch.setNoticeDepartment(departmentList);
        dispatch.setNoticeUsers(userList);
        dispatch.setFile(fileManageList);
        dispatch.setCompany(user.getCompany());
        return  dispatch;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String typedictId, String title,
                       String fileNo, String time, String object, String hasValid, String validDate,
                       String noticeDepartmentId, String noticeUserId, String fileIds) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Dispatch dispatch = setData(user, keyId, typedictId, title, fileNo,
                time,object,hasValid,validDate,noticeDepartmentId, noticeUserId,fileIds);
        if(StringUtils.isNotEmpty(keyId)){
            dispatchService.update(dispatch);
            rMap.put("message", "更新成功");
        } else {
            dispatchService.save(dispatch, "com.fz.us.oa.core.entity.com.Dispatch");
            rMap.put("message","保存成功");
        }
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }


    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String typedictId, String title,
                         String fileNo, String time, String object, String hasValid, String validDate,
                         String noticeDepartmentId, String noticeUserId, String fileIds, String curDutyId, String comment) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Dispatch dispatch = setData(user, keyId, typedictId, title, fileNo,
                time,object,hasValid,validDate,noticeDepartmentId, noticeUserId,fileIds);

        if (StringUtils.isNotEmpty(keyId)) {
            dispatchService.approve(dispatch, dutyService.get(curDutyId), comment);
        } else {
            dispatchService.commit(dispatch,"com.fz.us.oa.core.entity.com.Dispatch", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment,String mulExam,String examUsersId,String examObjectId,String leaderExam){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Dispatch dispatch = dispatchService.get(keyId);
        if(StringUtils.isNotEmpty(mulExam)){
            List<User> usersList = Lists.newArrayList();
            Set<Duty> examDutySet = Sets.newHashSet();
            Set<Duty> examDutySet2 = Sets.newHashSet();
            String dutyChooseIds = "";
            String dutyLeadIds = "";
            if(StringUtils.isNotEmpty(examUsersId)){
                String[] idArr = examUsersId.split(",");
                for(String id:idArr){
                    usersList.add(userService.get(id.trim()));
                    examDutySet.addAll(dutyService.getDutys(userService.get(id.trim())));
                }
            }
            List<Power> powerList = Lists.newArrayList();
            if(StringUtils.isNotEmpty(examObjectId)){
                String[] idArr =examObjectId.split(",");
                for(String id:idArr){
                    Power power = powerService.get(id.trim());
                    powerList.add(power);
                    List<Duty> dutyList = dutyService.getDutyListByPower(power);
                    for(Duty duty:dutyList) {
                        examDutySet2.add(duty);
                    }
                }
            }
            for(Duty duty:examDutySet){
                dutyChooseIds += duty.getId()+",";
            }
            if(StringUtils.isNotEmpty(dutyChooseIds)){
                dutyChooseIds = dutyChooseIds.substring(0, dutyChooseIds.length()-1);
            }
            for(Duty duty:examDutySet2){
                dutyLeadIds += duty.getId()+",";
            }
            if(StringUtils.isNotEmpty(dutyLeadIds)){
                dutyLeadIds = dutyLeadIds.substring(0, dutyLeadIds.length()-1);
            }
            dispatch.setDutyChooseIds(dutyChooseIds);
            dispatch.setDutyLeadIds(dutyLeadIds);
            dispatch.setMulExam(StringUtils.equals(mulExam, "1") ? true : false);
            dispatch.setLeaderExam(StringUtils.equals(leaderExam, "1") ? true : false);
            dispatch.setExamUsers(usersList);
            dispatch.setExamObject(powerList);
        }
        dispatchService.approve( dispatch, dutyService.get(curDutyId), comment);
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Dispatch dispatch = dispatchService.get(keyId);
            dispatchService.back(dispatch, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Dispatch dispatch = dispatchService.get(keyId);
            dispatchService.deny(dispatch, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                     String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;
        if(viewtype !=null && viewtype.equals("2")){
            order = Order.order("modifyTime", SearchEnum.OrderType.desc);
        }
        /*
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }*/
        SearchResultPaging searchResult = null;
       // List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                params.put("invalid", false);
                searchResult = dispatchService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Dispatch", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //已归档
                searchResult = dispatchService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Dispatch", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                searchResult = dispatchService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Dispatch", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed,FlowEnum.ProcessState.Finished}, params);
            }
        }else{
            //所有单子
            searchResult = dispatchService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.Dispatch",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<Dispatch> dispatchList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Dispatch dispatch: dispatchList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",dispatch.getId());
            rMap.put("type",dispatch.getType() != null?dispatch.getType().getName():"");
            rMap.put("fileNo",dispatch.getFileNo());
            rMap.put("title",dispatch.getTitle());
            rMap.put("time", DataUtil.DateToString(dispatch.getTime()));
            rMap.put("creater", dispatch.getCreater() != null ? dispatch.getCreater().getName() : "");
            rMap.put("createTime", DataUtil.DateToString(dispatch.getCreateTime(),"yyyy-MM-dd"));
            rMap.put("state",dispatch.getProcessState().value());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }



}
